package com.springapp.mvc.dao;

import com.springapp.mvc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by dbychkov on 19.12.2014.
 */
@Component
public class UserDaoImpl implements UserDao{

    @Autowired
    private JdbcTemplate template;

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }

    @Override
    public User getUserByName(String name) {
        String query = "SELECT * FROM users WHERE name = ?";
        return template.queryForObject(query, Mappers.USER_MAPPER, name);
    }

    @Override
    public User getUserById(Long id) {
        String query = "SELECT * FROM users WHERE id = ?";
        return template.queryForObject(query, Mappers.USER_MAPPER, id);
    }

    @Override
    public List<User> getAllUsers() {
        return template.query("SELECT * FROM users", Mappers.USER_MAPPER);
    }

    @Override
    public long createUser(String name, String hashedPassword, Long groupId){
        template.update("INSERT INTO users(name, password, group_id) values (?, ?, ?)",
                new Object[]{name, hashedPassword, groupId});
        return template.queryForLong("select last_insert_id()");
    }
}
